//index.js
//获取应用实例
const app = getApp();

let req = require('../../utils/request.js');
let api = require('../../utils/api.js');
let area = require('../../utils/area.js');

Page({
  data: {
    checked: '',
    phoneNumber: '',
    codeMsg: '获取验证码',
    code: '',
    iscountingDown: false,
    disabled: "disabled",
    welcoming: '感谢您对我们的支持',
    area: '+86 中国大陆',
    index: 0
  },
  onLoad: function () {
    var _this = this,
      area_arr = area.phone_reg,
      reg = [], areas = [], area_code = []
    
    //显示读取状态
    wx.showLoading({
      title: '加载中，请稍候',
    })

    //获取地区信息
    for(var i in area_arr) {
      var exploded_area_key = i.split('-')
      areas.push(exploded_area_key[1])
      area_code.push(exploded_area_key[2])
      reg.push(area_arr[i])
    }
    _this.setData({reg: reg, areas: areas, area_code: area_code});

    //检查用户登录态
    wx.checkSession({
      success: function () {
        //仍在登录状态，检查用户信息，没有问题则直接跳转至首页
        wx.getStorage({
          key: 'userInfo',
          success: function(res) {
            
            var userInfo = res.data
            app.globalData.userInfo = userInfo;
            if(userInfo.user_status == 1) {       //用户
              wx.redirectTo({
                url: '/pages/map/map',
              })
            } else if(userInfo.user_status == 2) {     //商户
              wx.redirectTo({
                url: '/pages/map/map',
              })
            }else {
              wx.hideLoading();
              _this.setData({ 'loading': 'loaded', step_1: 'hide', step_2: 'show', welcoming: '欢迎' })
            }
          },
          fail: function(res) {
            wx.hideLoading();
            _this.setData({'loading': 'loaded'})
          }
        })
      },
      fail: function () {
        //不在登录状态，执行登录流程
        wx.hideLoading();
        _this.setData({ 'loading': 'loaded' })
      }
    })
  },
  gotUserInfo: function(e) {
    var _this = this
    if(e.detail.errMsg.search('ok') != -1) {
      var userInfo = e.detail.userInfo
      //要求授权地理位置
      wx.authorize({
        scope: 'scope.userLocation',
        success: function() {
          //showloading
          wx.showLoading({
            title: '加载中，请稍候',
          })

          //调用登录接口
          app.login(userInfo, function(res) {
            var login_res = res.data;

            if (login_res.code != 1 && login_res.code != 0) {     //登陆失败
              wx.hideLoading();
              wx.showToast({
                title: '登录失败...',
                icon: 'none',
                duration: 2000
              })
            } else {                                              //登陆成功
              userInfo['user_token'] = login_res.user_info.user_token
              userInfo['user_status'] = login_res.user_info.user_status
              userInfo['user_discount_code'] = login_res.user_info.user_discount_code

              //将用户信息赋值到全局
              app.globalData.userInfo = userInfo

              //存储用户信息
              wx.setStorage({
                key: 'userInfo',
                data: userInfo
              })
              if (login_res.code == 1 && login_res.user_info.user_status == 1) {    //用户已存在且已绑定手机号，直接去首页
                wx.redirectTo({
                  url: '/pages/map/map',
                })
              }else if (login_res.code == 1 && login_res.user_info.user_status == 2) {
                wx.redirectTo({
                  url: '/pages/map/map',
                })
              }else if (login_res.code != 1) {
                wx.showToast({
                  title: '登录失败！请清理微信缓存后重试。',
                  icon: 'none'
                })
              }else {   //新用户或未完成手机号绑定者，完善信息
                wx.hideLoading();
                _this.setData({ step_1: 'hide', step_2: 'show' })
              }
            }
          });
          
        },
        fail: function() {
          wx.showToast({
            title: '您需要同意我们获取您的地理位置才能继续使用',
            icon: 'none',
            duration: 3000
          })
        }
      })
    }else {
      wx.showToast({
        title: '您需要同意我们获取您的信息才能继续使用',
        icon: 'none',
        duration: 3000
      })
    }
  },
  checkLegal(e) {
    var _this = this,
      index = _this.data.index,
      reg = _this.data.reg[index],
      area_code = _this.data.area_code[index],
      val = '+' + area_code + e.detail.value,
      data = {},
      isLegal = reg.test(val);
    if (isLegal && !_this.data.isCountingDown) {
      data['checked'] = 'checked';
      data['phoneNumber'] = val;
    } else {
      data['checked'] = '';
      data['phoneNumber'] = val;
    }
    _this.setData(data);

    //检查是否可以提交表单
    if (isLegal && _this.data.code == _this.data.currentCode) _this.setData({ disabled: '' });
    else _this.setData({ disabled: 'disabled' });

  },
  getCode() {
    var _this = this,
      checked = _this.data.checked,
      index = _this.data.index,
      reg = _this.data.reg[index],
      time = 59,
      f = null
    
    if (checked == 'checked' && !_this.data.isCountingDown) {
      wx.showLoading({
        title: '发送中',
      })
      //TODO 发起网络请求，请求验证码
      var getPhoneCode = api.getPhoneCode
      req.request(
        getPhoneCode, 
        {method: 'POST', data: {
          'phone': _this.data.phoneNumber
        }},
        function(res) {
          var result = res.data
          wx.hideLoading();
          //提示
          wx.showToast({
            title: result.msg,
            icon: 'none',
            duration: 2000
          });

          if(result.status == 1) {
            //将正确的码赋值到page
            _this.setData({ currentCode: result.code });
          }

          //分钟级流控
          f = setInterval(function () {
            _this.setData({
              codeMsg: time + 's后重发',
              checked: '',
              isCountingDown: true
            });
            if (time < 0) {
              var data = {};
              clearInterval(f);
              data['codeMsg'] = '重新发送';
              data['isCountingDown'] = false;

              if (reg.test(_this.data.phoneNumber)) {
                data['checked'] = 'checked';
              }
              _this.setData(data);
            }
            time--;
          }, 1000);
        }
      );
    }
  },
  checkCode(e) {
    //验证所有输入框是否都已输入且合法
    var code = e.detail.value,
      _this = this,
      phone = _this.data.phoneNumber,
      index = _this.data.index,
      reg = _this.data.reg[index],
      currentCode = _this.data.currentCode
    _this.setData({ code: code });
    if (code == currentCode && reg.test(phone)) 
      _this.setData({ disabled: '' });
    else 
      _this.setData({ disabled: 'disabled' });
  }, 
  submit() {
    var _this = this
    wx.showLoading({
      title: '加载中',
    })
    req.request(
      api.supplyInfo,
      {'method': 'POST', 'data': {
        phone: _this.data.phoneNumber,
        user_token: app.globalData.userInfo.user_token
      }},
      function(res) {
        wx.hideLoading();
        var result = res.data
        wx.showToast({
          title: result.msg,
          icon: 'none',
          duration: 2000
        })

        if(result.status == 1) {
          //更新缓存
          wx.getStorage({
            key: 'userInfo',
            success: function (res) {
              res = res.data
              res.user_status = 1

              wx.setStorageSync('userInfo', res)
              app.globalData.userInfo.user_status = 1
              setTimeout(function () {
                wx.redirectTo({
                  url: '/pages/map/map',
                })
              }, 2500)
            },
          })
          
          //跳转页面
          setTimeout(function() {
            wx.redirectTo({
              url: '/pages/map/map',
            })
          }, 2200);
        }
      }
    );
  },
  toBeSeller() {
    wx.redirectTo({
      url: '/pages/seller/index',
    })
  },
  selectArea(e) {
    var _this = this,
        index = e.detail.value,
        areas = _this.data.areas,
        area_code = _this.data.area_code,
        area = '+' + area_code[index] + '  ' + areas[index]
    
    _this.setData({area: area, index: index})
  },
  declareDetail() {
    wx.navigateTo({
      url: 'declares?id=1',
    })
  }
})
